package com.meizu.asum.richtextsdk.tools.selectpictools.selecter;

import android.app.Activity;
import android.content.Intent;

import com.meizu.asum.richtextsdk.tools.selectpictools.tools.SelectTools;
import com.meizu.asum.richtextsdk.tools.selectpictools.tools.UriTools;
import com.meizu.asum.richtextsdk.tools.selectpictools.vo.MediaVO;

/**
 * 系统图片获取操作类
 *
 * @Author XJW
 * @CreateTime 2017/6/2
 */
public class XPictureSelector {
    public static final int REQUEST_CODE_CAMERA_IMAGE = 100137;
    public static final int REQUEST_CODE_GALLERY_IMAGE = 100138;
    public static final int REQUEST_CODE_CROP_IMAGE = 100139;

    private Activity activity;
    private MediaVO mediaVO;
    private XPictureSelectorCallBack callBack;

    public XPictureSelector(Activity activity) {
        this.activity = activity;
        mediaVO = new MediaVO();
    }

    public XPictureSelector needCrop(boolean needCrop) {
        mediaVO.setNeedCrop(needCrop);
        return this;
    }

    public XPictureSelector proportion(double x, double y) {
        mediaVO.setScaleW(x);
        mediaVO.setScaleH(y);
        return this;
    }

    public XPictureSelector cachePath(String cachePath) {
        mediaVO.setCachePath(cachePath);
        return this;
    }

    public void fromPicture(XPictureSelectorCallBack callBack) {
        this.callBack = callBack;
        SelectTools.fromGallery(activity);
    }

    public void fromCamera(XPictureSelectorCallBack callBack) {
        this.callBack = callBack;
        mediaVO.setUri(SelectTools.fromCamera(activity));
    }

    public void disposeResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_GALLERY_IMAGE && resultCode == Activity.RESULT_OK) {// 图片已选取
            if (mediaVO.isNeedCrop()) {
                mediaVO.setUri(data.getData());
                CropPicture.cropImage(activity, mediaVO);
            } else {
                if (callBack != null) {
                    callBack.complete(true, UriTools.getFileUriFromMediaUri(activity, data.getData()));
                }
            }
        }

        if (requestCode == REQUEST_CODE_CAMERA_IMAGE && resultCode == Activity.RESULT_OK) {// 图片已拍
            if (mediaVO.isNeedCrop()) {
                CropPicture.cropImage(activity, mediaVO);
            } else {
                if (callBack != null) {
                    callBack.complete(true, mediaVO.getUri());
                }
            }
        }

        if (requestCode == REQUEST_CODE_CROP_IMAGE) {// 图片已裁切
            if (callBack != null) {
                if (CropPicture.getUri() != null) {
                    callBack.complete(true, CropPicture.getUri());
                } else {
                    callBack.complete(false, null);
                }
            }
        }
    }
}
